package com.ly.crawl;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.DispatcherServlet;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@ComponentScan("com.ly.crawl")
@ConditionalOnClass({DispatcherServlet.class, JdbcTemplate.class})
@ConfigurationProperties(prefix = "ly.crawl.datasource")
public class CrawlConfig {

    private String url;
    private String driverClassName;
    private String username;
    private String password;

    @Resource
    private DataSource dataSource;

    DataSource getLoginDataSource() {
        if (url == null) {
            return dataSource;
        } else {
            DriverManagerDataSource ds = new DriverManagerDataSource(url, username, password);
            ds.setDriverClassName(driverClassName);
            return ds;
        }
    }

    @Bean
    @ConditionalOnProperty(value = "ly.crawl.datasource.url")
    @ConditionalOnMissingBean(JdbcTemplate.class)
    JdbcTemplate jdbc() {
        return new JdbcTemplate(getLoginDataSource());
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
